package org.numb.concurrency.chapter03;

import java.util.concurrent.atomic.AtomicReference;

public class SpinLock {

    private AtomicReference<Thread> cas = new AtomicReference<>();

    public void lock() {
        Thread thread = Thread.currentThread();
        // 利用CAS加锁失败则自旋
        while (!cas.compareAndSet(null, thread)) {
            // 自旋，可以等待或者什么都不做
        }

    }

    public void unlock() {
        Thread thread = Thread.currentThread();
        cas.compareAndSet(thread, null);
    }
}
